package com.cats.template.sys.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cats.template.sys.pojo.dto.RoleDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author duxiaobo
 * @date 2021/9/83:02 下午
 */
@Slf4j
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {
    //过期时间
    private static Long expire;
    private static String ALGORITHMNAME = "md5";
    private static Integer HASHITERATIONS = 1;

    @Value("${jwt.expire}")
    public void setExpireValue(Long expireValue) {
        expire = expireValue;
    }

    // 秘钥

    private static String secret;

    @Value("${jwt.secret}")
    public void setSecretValue(String secretValue) {
        secret = secretValue;
    }


    /**
     * 校验token是否正确
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            //根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWT.require(algorithm).build().verify(token);
            return true;
        } catch (UnsupportedEncodingException e) {
            return false;
        }
    }

    /**
     * 获取token中的信息无需secret解密也能获得
     *
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userName").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static List<RoleDto> getRoles(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("roles").asList(RoleDto.class);
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取用户id
     *
     * @param token
     * @return
     */
    public static Long getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名
     *
     * @param map
     * @return
     */
    public static String sign(Map<String, String> map) {
        try {
            Date date = new Date(System.currentTimeMillis() + expire * 1000);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTCreator.Builder builder = JWT.create();
            map.forEach((k, v) -> {
                builder.withClaim(k, v);
            });
            return builder.withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String encryptPassword(String password, String salt) {
        String newPassword = new SimpleHash(ALGORITHMNAME, password,
                ByteSource.Util.bytes(salt), HASHITERATIONS).toHex();
        return newPassword;
    }

    public static String roundSalt() {
        return UUID.randomUUID().toString();
    }

    public static Long getExpire() {
        return expire;
    }

    public static void setExpire(Long expire) {
        JwtUtils.expire = expire;
    }

    public static String getSecret() {
        return secret;
    }

    public static void setSecret(String secret) {
        JwtUtils.secret = secret;
    }


}
